package com.lyshop.jinxiang.utils;

import android.os.CountDownTimer;
import android.os.Handler;
import android.widget.Button;
import android.widget.TextView;

public class TimeCount extends CountDownTimer {
    private TextView mTextView;
    private Button mButton;
    private String msg;
    private Handler mHandler = new Handler();

    /**
     *
     * @param millisInFuture 总时间
     * @param countDownInterval 间隔
     */
    public TimeCount(long millisInFuture, long countDownInterval) {
        this(null, millisInFuture, countDownInterval, "");
    }

    public TimeCount(long millisInFuture, long countDownInterval, TickListener listener) {
        this(null, millisInFuture, countDownInterval, "");
        this.mListener = listener;
    }

    public TimeCount(TextView textView, long millisInFuture, long countDownInterval, String msg) {
        super(millisInFuture, countDownInterval);
        this.mTextView = textView;
        this.msg = msg;
        if (textView != null) {
            textView.setEnabled(false);
        }
    }

    public TimeCount(Button btn, long millisInFuture, long countDownInterval, String msg) {
        super(millisInFuture, countDownInterval);
        this.mButton = btn;
        this.msg = msg;
        if (mButton != null) {
            mButton.setEnabled(false);
        }
    }

    @Override
    public void onTick(long millisUntilFinished) {
        if (mButton != null) {
            mButton.setText(String.format("剩余%s秒", String.valueOf(millisUntilFinished / 1000)));
        }
        if (mTextView != null) {
            mTextView.setText(String.format("剩余%s秒", String.valueOf(millisUntilFinished / 1000)));
        }

        if (null != mListener) {
            mListener.onTick(millisUntilFinished);
        }
    }

    @Override
    public void onFinish() {
        if (mButton != null) {
            mButton.setEnabled(true);
            mButton.setText(msg);
        }
        if (mTextView != null) {
            mTextView.setEnabled(true);
            mTextView.setText(msg);
        }
        if (null != mListener) {
            mListener.onFinish();
        }
    }


    public void finishTimeCount() {
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                TimeCount.this.onFinish();
                TimeCount.this.cancel();
            }
        });
    }

    private TickListener mListener;

    public interface TickListener {
        void onTick(long millisUntilFinished);

        void onFinish();
    }
}
